package com.ms.demo.service.impl;

import com.ms.demo.entity.Book;
import com.ms.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description: ***
 * @author: ms
 * @create: 2022-09-14 14:35
 */
@Service
public class BookServiceImpl implements BookService {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    //@Transactional
    public void buyBook(Integer bookId, Integer userId) {

        //1-查询图书的价格
        String sql1 = "select * from t_book where book_id = ?";
        Book book = jdbcTemplate.queryForObject(sql1, new BeanPropertyRowMapper<>(Book.class), bookId);
        Integer price = (book == null ? 0 : book.getPrice());
        System.out.println("bookId为："+ bookId +"的图书，价格为："+ price);
        //2-更新图书的库存
        String sql2 = "update t_book set stock = stock - 1 where book_id = ?";
        jdbcTemplate.update(sql2, bookId);
        //3-更新用户的余额
        String sql3 = "update t_user set balance = balance - ? where user_id = ?";
        jdbcTemplate.update(sql3, price, userId);

    }

}